package com.atcd.security_redis_jwt.util;

import com.alibaba.fastjson.JSON;

import com.atcd.security_redis_jwt.bean.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;


public class JwtUtil {
    //hmac256摘要算法，跟md5类似，只是这个hmac256需要你指定一个key而已(随便写的)
  private static  final String Key ="twtjh15583162269";


    //生成的token
    public  static  String createToken(String userid){

        Calendar calendar = Calendar.getInstance();

        calendar.add(Calendar.DAY_OF_YEAR,7);
        //claim：声明
        JWTCreator.Builder builder = JWT.create()
                .withClaim("userInfo", userid);


        //设置token的过期时间(假设7天),从生成开始计算，超过时间，不能再解析token
        String token = builder.withExpiresAt(calendar.getTime())
                //签名
                .sign(Algorithm.HMAC256(Key));

        return token;
    }

    //校验token
    public  static String  verifyToken(String CheckedToken){
        DecodedJWT verify=null;
        try{
            verify = JWT.require(Algorithm.HMAC256(Key)).build().verify(CheckedToken);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("token异常");
        }
        //不为空，返回被校验的token,再在外面使用verify.getClaim("userInfo").asString()来获取
//       return verify;

        return parseToken(verify);
    }

    //解析token
    public  static  String parseToken(DecodedJWT verify){
        Claim claim = verify.getClaim("userInfo");
        if(claim!=null){
            String UserString = claim.asString();
           return UserString;
        }
        //为空直接返回null
        return null;
    }
}
